﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SBB.Services.SFTP.Server.Data
{
    public class SQLHandler : IDisposable
    {
        private SqlConnection _conn = null;

        public SQLHandler()
        {
            _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString);
            _conn.Open();
        }

        public void SaveFile(string username, byte[] file, string extension)
        {
            var sql = new StringBuilder();

            using (SqlCommand cmd = new SqlCommand("INSERT INTO Upload (Id, Username, [File], FileExtension) VALUES (@ID, @Username, @File, @FileExtension)", _conn)) {
                cmd.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value = Guid.NewGuid();
                cmd.Parameters.Add("@Username", SqlDbType.VarChar, -1).Value = username;
                cmd.Parameters.Add("@File", System.Data.SqlDbType.VarBinary, -1).Value = file;
                cmd.Parameters.Add("@FileExtension", SqlDbType.VarChar, 5).Value = extension;
                cmd.ExecuteNonQuery();
            }

        }

        public void Dispose()
        {
            if (_conn != null) {
                _conn.Close();
                _conn.Dispose();

                _conn = null;
            }
        }
    }
}
